<?php
/**
 * Created by PhpStorm.
 * User: nfangxu
 * Date: 2019/1/17
 * Time: 14:34
 */

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\ProductSkuAttribute;
use Illuminate\Http\Request;
use App\Models\Carousel;
use App\Models\Category;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class ApiController extends Controller
{
    public function products(Request $request)
    {
        $q = $request->get('q');

        return Product::query()
            ->where('name', 'like', "%{$q}%")
            ->paginate(null, ['id', 'name as text']);
    }

    public function attributes(Request $request)
    {
        $q = $request->get('q');
        return ProductSkuAttribute::query()->whereProductId($q)->options();
    }

    public function carouselType(Request $request)
    {
        $type = $request->get('q');

        switch ($type) {
            case Carousel::TYPE_CATEGORY:
                return Category::get(['id', DB::raw('name as text')]);
                break;
            case Carousel::TYPE_PRODUCT:
                return Product::get(['id', DB::raw('name as text')]);
                break;
        }

        return [];
    }

    public function upload(Request $request)
    {
        $file = $request->file('upload_file');

        $path = Storage::disk(config('admin.upload.disk'))->putFile('products', $file);

        $url = Storage::disk(config('admin.upload.disk'))->url($path);

        return [
            'file_path' => $url,
        ];
    }
}
